using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using Microsoft.Robotics.PhysicalModel.Proxy;
using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Permissions;

using Microsoft.Dss.Core.DsspHttpUtilities;
using System.Collections.Specialized;

using W3C.Soap;
using encoder = Microsoft.Robotics.Services.Encoder.Proxy;
using vex = VEXRobotics.Proxy;
using submgr = Microsoft.Dss.Services.SubscriptionManager;

/* Notes on VEX Encoder
 *   Identifier must be the interrupt port number on the VEX. Range: 1 - 6.
 *   TicksPerRevolution is 90.
 */
namespace VEXService.Encoder
{
    [ServicePort]
    public class VEXEncoderOperations : PortSet<
        DsspDefaultLookup,
        DsspDefaultDrop,
        encoder.ReliableSubscribe,
        encoder.Subscribe,
        Get,
        encoder.Reset,
        encoder.UpdateTickCount,
        encoder.Replace, 
        HttpGet,
        HttpPost>
    {
    }

    /// <summary>
    /// Get the state
    /// </summary>
    [DataContract]
    public class Get : Get<GetRequestType, PortSet<VEXEncoderState, Fault>>
    {
    }

    // Summary:
    //     Definition of a wheel encoder
    [DataContract]
    [Description("The state of the encoder.")]
    public class VEXEncoderState : IDssSerializable, ICloneable
    {
        private string _Name;
        private double _CurrentAngle;
        private int _CurrentReading;
        private vex.InterruptPort _InterruptPort;
        private int _TicksPerRevolution;
        private int _TicksSinceReset;
        public int TicksLastRead;
        private DateTime _TimeStamp;
        private Pose _Pose;

        public VEXEncoderState()
        {
            _TicksPerRevolution = 90;
            TicksLastRead = 0;
            _TimeStamp = DateTime.MinValue;
            _Pose = new Pose();
        }

        //
        // Summary:
        //     Interrupt port identifier
        [DataMemberConstructor(Order = 1)]
        [Description("Identifies the interrupt port.")]
        [DataMember]
        public vex.InterruptPort InterruptPort
        {
            get { return _InterruptPort; }
            set { _InterruptPort = value; }
        }

        /// <summary>
        /// Specifies the descriptive identifier for the encoder.
        /// </summary>
        [DataMember]
        [Description("Specifies a user friendly name for the VEX Encoder.")]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        // Summary:
        //     Current reading in terms of angle, in radians.
        //
        // Remarks:
        //     Valid if TicksPerRevolution set
        [Browsable(false)]
        [Description("Indicates the current angle reading (in radians).")]
        [DataMember(Order = -1)]
        public double CurrentAngle
        {
            get { return _CurrentAngle; }
            set { _CurrentAngle = value; }
        }

        //
        // Summary:
        //     Current reading, in ticks
        [DataMember(Order = -1)]
        [Description("Indicates the current encoder reading (in ticks).")]
        [Browsable(false)]
        public int CurrentReading
        {
            get { return _CurrentReading; }
            set { _CurrentReading = value; }
        }

        //
        // Summary:
        //     Number of increments since last reset
        [Browsable(false)]
        [Description("Specifies the number of increments since last reset.")]
        [DataMember(Order = -1)]
        public int TicksSinceReset
        {
            get { return _TicksSinceReset; }
            set { _TicksSinceReset = value; }
        }

        //
        // Summary:
        //     Timestamp of this sample
        [DefaultValue(typeof(DateTime), "0001-01-01T00:00:00")]
        [Description("Identifies the timestamp of the encoder reading.")]
        [Browsable(false)]
        [DataMember(Order = -1, XmlOmitDefaultValue = true)]
        public DateTime TimeStamp
        {
            get { return _TimeStamp; }
            set { _TimeStamp = value; }
        }

        /// <summary>
        /// Pose of the encoder
        /// </summary>
        [DataMember]
        [Description("The position and orientation of the encoder.")]
        public Pose Pose
        {
            get { return _Pose; }
            set { _Pose = value; }
        }


        /// <summary>
        /// Transform current state to the specified generic state.
        /// </summary>
        /// <param name="genericState"></param>
        /// <returns></returns>
        public encoder.EncoderState ToGenericState(encoder.EncoderState genericState)
        {
            genericState.CurrentAngle = this.CurrentAngle;
            genericState.CurrentReading = this.CurrentReading;
            genericState.HardwareIdentifier = (int)this.InterruptPort;
            genericState.TicksPerRevolution = 90;
            genericState.TicksSinceReset = this.TicksSinceReset;
            genericState.TimeStamp = this.TimeStamp;
            return genericState;
        }

        /// <summary>
        /// Copy generic state to this state, transforming data members.
        /// </summary>
        /// <param name="genericState"></param>
        public void FromGenericState(encoder.EncoderState genericState)
        {
            this.CurrentAngle = genericState.CurrentAngle;
            this.CurrentReading = genericState.CurrentReading;
            this.TimeStamp = genericState.TimeStamp;
        }


        #region IDssSerializable

        /// <summary>
        /// Copy To Analog Input sensor state
        /// </summary>
        public virtual void CopyTo(IDssSerializable target)
        {
            VEXEncoderState typedTarget = target as VEXEncoderState;

            if (typedTarget == null)
                throw new ArgumentException("CopyTo({0}) requires type {0}", this.GetType().FullName);

            typedTarget.CurrentAngle = this.CurrentAngle;
            typedTarget.CurrentReading = this.CurrentReading;
            typedTarget.InterruptPort = this.InterruptPort;
            typedTarget.Name = this.Name;
            typedTarget.Pose = this.Pose;
            typedTarget.TicksSinceReset = typedTarget.TicksSinceReset;
            typedTarget.TimeStamp = typedTarget.TimeStamp;
        }

        /// <summary>
        /// Clone the VEX Encoder State
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            VEXEncoderState clone = new VEXEncoderState();
            clone.CurrentAngle = this.CurrentAngle;
            clone.CurrentReading = this.CurrentReading;
            clone.InterruptPort = this.InterruptPort;
            clone.Name = this.Name;
            clone.Pose = this.Pose;
            clone.TicksSinceReset = this.TicksSinceReset;
            clone.TimeStamp = this.TimeStamp;

            return clone;
        }

        /// <summary>
        /// Serialize
        /// </summary>
        public virtual void Serialize(System.IO.BinaryWriter writer)
        {
            writer.Write(this.CurrentAngle);
            writer.Write(this.CurrentReading);
            writer.Write((int)this.InterruptPort);
            writer.Write(this.Name);
            Pose.Serialize(writer);
            writer.Write(this.TicksSinceReset);
            Microsoft.Dss.Services.Serializer.BinarySerializationHelper.SerializeDateTime(TimeStamp, writer);
        }

        /// <summary>
        /// Deserialize
        /// </summary>
        public virtual object Deserialize(System.IO.BinaryReader reader)
        {
            Name = reader.ReadString();
            
            this.CurrentAngle = reader.ReadDouble();
            this.CurrentReading = reader.ReadInt32();
            this.InterruptPort = (vex.InterruptPort)reader.ReadInt32();
            this.Name = reader.ReadString();
            Pose.Deserialize(reader);
            this.TicksSinceReset = reader.ReadInt32();
            TimeStamp = Microsoft.Dss.Services.Serializer.BinarySerializationHelper.DeserializeDateTime(reader);

            return this;
        }
        #endregion
    }

    [Contract(Contract.Identifier)]
    [AlternateContract(encoder.Contract.Identifier)]
    [DisplayName("VEX Encoder")]
    [Description("Provides access to the VEX motor encoder.")]
    [DssServiceDescription("http://msdn.microsoft.com/en-us/library/dd145252.aspx")]
    [DssCategory(vex.VEXCategories.VEX)]
    public class VEXEncoderService : DsspServiceBase
    {
        /// <summary>
        /// XSLT Transform to use for display
        /// </summary>
        [EmbeddedResource("VEXService.Config.Encoder.xslt")]
        private string _transform = null;

        /// <summary>
        /// Sensor state
        /// </summary>
        [InitialStatePartner(Optional = true, ServiceUri = ServicePaths.Store + @"/VEX.Encoder.Config.xml")]
        VEXEncoderState _State = null;

        /// <summary>
        /// Service port
        /// </summary>
        [ServicePort("/VEX/Encoder", AllowMultipleInstances = true)]
        private VEXEncoderOperations _mainPort = new VEXEncoderOperations();

        /// <summary>
        /// Alternate port for the generic port
        /// </summary>
        [AlternateServicePort("/encoder",
            AllowMultipleInstances = true,
            AlternateContract = encoder.Contract.Identifier)]
        private encoder.EncoderOperations _genericPort = new encoder.EncoderOperations();

        /// <summary>
        /// Port to talk with the VEX controller
        /// </summary>
        [Partner("VEX", Contract = vex.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate,
            Optional = false)]
        private vex.VEXOperations _vexPort = new vex.VEXOperations();

        // Create a notification port
        vex.VEXOperations _notificationPort = new vex.VEXOperations();

        /// <summary>
        /// HTTP helper
        /// </summary>
        DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort();

        /// <summary>
        /// Subscription manager
        /// </summary>
        [Partner("SubMgr", Contract = submgr.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.CreateAlways,
            Optional = false)]
        submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="creationPort"></param>
        public VEXEncoderService(DsspServiceCreationPort creationPort)
            : base(creationPort)
        {
        }

        #region Initialization Code

        /// <summary>
        /// Startup
        /// </summary>
        protected override void Start()
        {
            LogVerbose(LogGroups.Console, "Configuring VEX Encoder... ");

            #region Initialize Service State
            if (_State == null)
            {
                _State = new VEXEncoderState();
                SaveState(_State);
            }
            #endregion

			base.Start();

            #region Initialize Service State
            // Reset the controller to know about our configuration
            Port<bool> donePort = new Port<bool>();
            SpawnIterator<Port<bool>>(donePort, InitializeKnownConnection);
            Activate(Arbiter.Receive(false, donePort,
                delegate(bool success)
                {
                    if (success)
                    {
                        // Display HTTP service Uri
                        LogInfo(LogGroups.Console, "Service uri: ");
                    }
                    else
                    {
                        LogError(LogGroups.Console, "VEX Encoder service failed to start.");
                        _mainPort.Post(new DsspDefaultDrop());
                    }
                }));
            #endregion

            // Needed for HttpPost
            _httpUtilities = DsspHttpUtilitiesService.Create(Environment);
        }

        /// <summary>
        /// Initialize this object based upon the current state.  Additionally,
        /// update the controller to our configuration
        /// </summary>
        /// <param name="resultPort"></param>
        /// <returns></returns>
        private IEnumerator<ITask> InitializeKnownConnection(Port<bool> resultPort)
        {
            bool serviceSuccess = true;

            // Configure default state
            if (_State.InterruptPort == vex.InterruptPort.InterruptPort_None)
            {
                serviceSuccess = false;
            }
            else
            {
                // Configure default state
                vex.SelectiveInterruptConfigure newConfig = new vex.SelectiveInterruptConfigure();
                newConfig.Body.Interrupt = _State.InterruptPort;
                newConfig.Body.Type = vex.SensorDefinition.SensorType.Encoder;

                _vexPort.Post(newConfig);
                yield return Arbiter.Choice(newConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });

                // Subscribe to VEX for notifications
                if (serviceSuccess)
                {
                    serviceSuccess = false;
                    SaveState(_State);
                    Port<bool> donePort = new Port<bool>();
                    SpawnIterator<Port<bool>>(donePort, SubscribeToVEX);
                    yield return (Arbiter.Receive<bool>(false, donePort,
                        delegate(bool subSuccess)
                        {
                            serviceSuccess = subSuccess;
                        }));
                }
            }

            resultPort.Post(serviceSuccess);
            yield break;
        }

        /// <summary>
        /// Subscribe to appropriate sensor type and port on VEX
        /// </summary>
        private IEnumerator<ITask> SubscribeToVEX(Port<bool> successPort)
        {
            // Create a custom subscription request
            vex.CustomSubscribeRequestType request = new vex.CustomSubscribeRequestType();

            // Select only the sensor and port we want
            // NOTE: this name must match the VEX sensor name.
            request.Sensors = new List<vex.SensorDefinition>();

            vex.SensorDefinition sensor = new vex.SensorDefinition();
            sensor.Type = vex.SensorDefinition.SensorType.Encoder;
            sensor.Port = vex.SensorPort.SensorPort_None;
            sensor.Interrupt = _State.InterruptPort;
            request.Sensors.Add(sensor);

            // Subscribe to the VEX and wait for a response
            bool subscribed = false;
            yield return
                Arbiter.Choice(_vexPort.SelectiveSubscribe(request, _notificationPort),
                    delegate(SubscribeResponseType Rsp)
                    {
                        // Start listening
                        base.MainPortInterleave.CombineWith(new Interleave(
                            new ExclusiveReceiverGroup(
                                Arbiter.Receive<vex.Update>(true, _notificationPort, SensorNotificationHandler)
                            ),
                            new ConcurrentReceiverGroup()));

                        //update our state with subscription status
                        subscribed = true;
                    },
                    delegate(Fault fault)
                    {
                        LogError("Digital output subscription failed", fault);
                        successPort.Post(false);
                    }
                );

            successPort.Post(subscribed);
            yield break;
        }

        #endregion

        /// <summary>
        /// Handle sensor update message from VEX
        /// </summary>
        public void SensorNotificationHandler(vex.Update notify)
        {
            if (_State.InterruptPort == vex.InterruptPort.InterruptPort_None)
            {
                LogError(_State.Name + ": No interrupt port selected");
                notify.ResponsePort.Post(
                    Fault.FromException(
                        new ArgumentException(
                            string.Format("Invalid Interrupt Port: {0}",
                                notify.Body.InterruptSensors))));
            }
            else
            {
                // Update time
                _State.TimeStamp = DateTime.Now;

                int newReading = (int)notify.Body.InterruptSensors.Sensors[(int)_State.InterruptPort - 1].Value;

                // Increment counter (and account for any missing ticks
                int delta = newReading - _State.TicksLastRead;
                _State.TicksSinceReset += Math.Abs(delta);
                _State.TicksLastRead = newReading;

                // Update angle
                _State.CurrentReading = newReading;
                _State.CurrentAngle = _State.CurrentReading % 90;
                _State.CurrentAngle = 2.0 * Math.PI * _State.CurrentAngle / 90.0;

                // Notify subscribers on any state change
                encoder.UpdateTickCount updateHeader = new encoder.UpdateTickCount(new encoder.UpdateTickCountRequest(DateTime.Now, _State.TicksSinceReset));
                SendNotification<encoder.UpdateTickCount>(_subMgrPort, updateHeader);
            }
        }

        /// <summary>
        /// Update notification from the controller about the current tick count
        /// </summary>
        /// <param name="updateTickCount"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> UpdateTickCountHandler(encoder.UpdateTickCount updateTickCount)
        {
            _State.CurrentReading = updateTickCount.Body.Count;
            updateTickCount.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public IEnumerator<ITask> GetHandler(Get get)
        {
            get.ResponsePort.Post(_State);
            yield break;
        }

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> GetHandler(encoder.Get get)
        {
            encoder.EncoderState genericState = new encoder.EncoderState();
            get.ResponsePort.Post(_State.ToGenericState(genericState));
            yield break;
        }

        /// <summary>
        /// Get the state to HTTP display
        /// </summary>
        /// <param name="httpGet">Response port to post the state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            httpGet.ResponsePort.Post(new HttpResponseType(
                HttpStatusCode.OK,
                _State,
                _transform)
            );
            yield break;
        }

        /// <summary>
        /// HttpPost Handler
        /// </summary>
        /// <param name="submit"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost)
        {
            // Use helper to read form data
            ReadFormData readForm = new ReadFormData(httpPost);
            _httpUtilities.Post(readForm);

            // Wait for result
            Activate(Arbiter.Choice(readForm.ResultPort,
                delegate(NameValueCollection parameters)
                {
                    if (parameters["Name"] != null)
                    {
                        // Update our state variables
                        _State.Name = parameters["Name"];
                    }
                    HttpPostSuccess(httpPost);
                },
                delegate(Exception fault)
                {
                    LogError(fault.Message);
                    HttpPostFailure(httpPost, fault.Message);
                })
            );
            yield break;
        }

        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        /// <param name="httpPost"></param>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _State, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        /// <param name="httpPost"></param>
        /// <param name="failureReason"></param>
        private static void HttpPostFailure(HttpPost httpPost, string failureReason)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.ExpectationFailed, failureReason);
            httpPost.ResponsePort.Post(rsp);
        }
        
        /// <summary>
        /// Reset the tick count
        /// </summary>
        /// <param name="reset"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ResetHandler(encoder.Reset reset)
        {
            _State.TicksSinceReset = 0;
            reset.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Replace the state with the given update
        /// </summary>
        /// <param name="replace">Replacement state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReplaceHandler(encoder.Replace replace)
        {
            if((int)_State.InterruptPort != replace.Body.HardwareIdentifier)
            {
                Fault fault = Fault.FromException(new InvalidOperationException("Cannot reassign sensor ports"));
                replace.ResponsePort.Post(fault);
                yield break;
            }
            _State.FromGenericState(replace.Body);
            SaveState(_State);

            encoder.EncoderState genericState = new encoder.EncoderState();
            SendNotification<encoder.Replace>(_subMgrPort, _State.ToGenericState(genericState));
            replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Subscribe to updates
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> SubscribeHandler(encoder.Subscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    encoder.EncoderState genericState = new encoder.EncoderState();
                    _State.ToGenericState(genericState);
                    SendNotification<encoder.Replace>(_subMgrPort, subscribe.Body.Subscriber, new encoder.Replace(genericState));
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }

        /// <summary>
        /// ReliableSubscribe Handler
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReliableSubscribeHandler(encoder.ReliableSubscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    encoder.EncoderState genericState = new encoder.EncoderState();
                    _State.ToGenericState(genericState);
                    SendNotification<encoder.Replace>(_subMgrPort, subscribe.Body.Subscriber, new encoder.Replace(genericState));
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }
    }

    /// <summary>
    /// VEX Encoder Contract 
    /// </summary>
    public sealed class Contract
    {
        public const string Identifier = "http://schemas.vexrobotics.com/2011/09/vexservice.encoder.html";
    }

}
